package com.pnnd.stream;

import com.pnnd.utils.IntList;

import java.util.List;
import java.util.Map;

public class Cache {

    private int cachePageCnt;
    private int availableCnt;
    private List<MemorySegment> segments;

    private Map<AbstractBuffer, IntList> bufferSegmentIndexMap;

    /**
     * 从缓存中获取指定内存页数的缓存，如果超出当前可用缓存页则执行相应的策略
     * @param requireSegmentCnt 申请的页数
     * @return buffer
     */
    public Buffer getBuffer(int requireSegmentCnt, boolean continuation){

        IntList segmentIndexes = new IntList(requireSegmentCnt);

        for(int i=0;i<this.segments.size();i++){
            MemorySegment segment = this.segments.get(i);

            if(segment.getOwner()!=null){
                segmentIndexes.add(i);
            }else{
                if(continuation)
                    segmentIndexes.clear();
            }

            if(segmentIndexes.size() == requireSegmentCnt){
                break;
            }
        }

        if(segmentIndexes.size() != requireSegmentCnt){
            throw new NoMoreMemoryInCacheException();
        }

        return null;
    }

    public void close(){
    }

    public int getCachePageCnt() {
        return this.cachePageCnt;
    }

    public int getAvailableCnt() {
        return this.availableCnt;
    }
}
